package com.example.demo.controller.nginx;

import com.example.demo.common.Nginx;
import com.example.demo.pojo.ConfigFile;
import com.example.demo.pojo.FileName;
import com.example.demo.pojo.NginxConf;
import com.example.demo.service.configfile.IConfigFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class NginxController {

    @Autowired
    IConfigFileService configFileService;

    private static final String NGINX_CONF_PATH = "/usr/local/nginx/conf/nginx.conf";

    // 首页，显示配置文件内容
    @GetMapping({"/", "/index"})
    public String index(Model model) {
        List<ConfigFile> configFiles = configFileService.list();
        model.addAttribute("configFiles", configFiles);
        return "index";
    }

    @GetMapping("/edit")
    public String edit(Model model,Integer id) {
        String filePath=configFileService.fingCofigFilePath(id);
        String nginxConfig = Nginx.readConfigFile(filePath);
        model.addAttribute("filePath", filePath);
        model.addAttribute("nginxConfig", nginxConfig);
        return "edit";
    }

    // 保存配置文件
    @PostMapping("/saveConfig")
    public String saveConfig(NginxConf nginxConf) {
        if (Nginx.writeConfigFile(nginxConf.getFilePath(), nginxConf.getNginxConfig())) {
            String testResult = Nginx.testConfig();
            if (!testResult.equals("配置正确！")) {
                return "error";
            }
            Nginx.restartNginx();
            return "redirect:/";
        } else {
            return "error";
        }

    }

    // 查看 Nginx 状态
    @GetMapping("/status")
    public String status(Model model) {
        String status = Nginx.getNginxStatus();
        model.addAttribute("status", status);
        return "status";
    }

    @GetMapping("/sitedir")
    public String sitedir(Model model,String path) {

        if(path==null){
            path=Nginx.getNginxDir();
        }

        List<String> nginxListDir = Nginx.getNginxListDir(path);
        List<FileName> paths = Nginx.splitPath(path);
        model.addAttribute("paths",paths);
        model.addAttribute("path", path);
        model.addAttribute("nginxListDir", nginxListDir);
        return "sitedir";
    }

    @GetMapping("/isDir")
    @ResponseBody
    public Map<String,Object> isDir(String path){
        Map<String,Object> map=new HashMap<>();
        File file = new File(path);
        if (file.isDirectory()) {
            map.put("code",200);
        } else {
            map.put("code",500);
        }
        return map;
    }


    @PostMapping("/saveConfigFile")
    public String saveConfigFile(ConfigFile configFile) {
        String filePath=configFile.getFilePath()+File.separator+configFile.getName()+".conf";
        System.out.println(filePath+"=====filePath");
        File file = new File(filePath);
        try {
            if (file.exists()) {
                System.out.println("文件已存在：" + filePath);
            } else {
                // 确保目录存在
                File parentDir = file.getParentFile();
                if (parentDir != null && !parentDir.exists()) {
                    if (parentDir.mkdirs()) {
                        System.out.println("创建目录：" + parentDir.getAbsolutePath());
                    } else {
                        System.err.println("目录创建失败：" + parentDir.getAbsolutePath());
                    }
                }
                // 创建文件
                if (file.createNewFile()) {

                    System.out.println("文件创建成功：" + filePath);
                } else {
                    System.err.println("文件创建失败：" + filePath);
                }
            }
        } catch (IOException e) {
            System.err.println("文件处理失败：" + filePath);
            e.printStackTrace();
        }
        configFile.setFilePath(filePath);
        configFileService.save(configFile);
        Nginx.restartNginx();
        return "redirect:/";
    }


//    @PostMapping("/add-site")
//    public String addSite(
//                          @RequestParam String directory
//                          ) {
//
//        try {
//            // 设置用户组
//            Process chownProcess = new ProcessBuilder("cd", "" ).start();
//            if (chownProcess.waitFor() != 0) {
//                return "设置用户组失败！";
//            }
//
//            // 设置权限
//            Process chmodProcess = new ProcessBuilder("chmod", permissions, directory).start();
//            if (chmodProcess.waitFor() != 0) {
//                return "设置权限失败！";
//            }
//
//            // 保存站点配置逻辑（可存储到数据库或文件中）
//            return "站点 " + siteName + " 添加成功！";
//
//        } catch (IOException | InterruptedException e) {
//            e.printStackTrace();
//            return "配置失败：" + e.getMessage();
//        }
//    }







}

